package com.whisperly.echotalk.account;

import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Bundle;
import android.os.Handler;
import android.os.LocaleList;
import android.os.Looper;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.google.android.material.snackbar.Snackbar;
import com.whisperly.echotalk.bllmodel.ChatHistory;
import com.whisperly.echotalk.bllmodel.UserQuery;
import com.whisperly.echotalk.bllmodel.UserWithChat;
import com.whisperly.echotalk.starryb.schemas.Login;
import com.whisperly.echotalk.starryb.R;
import com.whisperly.echotalk.starryb.utils.AppsManager;
import com.whisperly.echotalk.starryb.utils.DatabaseHelper;
import com.whisperly.echotalk.starryb.utils.GlobalData;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import cn.bmob.v3.BmobBatch;
import cn.bmob.v3.BmobObject;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.datatype.BatchResult;
import cn.bmob.v3.datatype.BmobQueryResult;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.QueryListListener;
import cn.bmob.v3.listener.SQLQueryListener;
import cn.bmob.v3.listener.UpdateListener;

public class Account extends AppCompatActivity {

    private LinearLayout user_info,updatePws ,clearAccount;
    private TextView login_out;
    private Toast currentToast;
    private UserWithChat user = new UserWithChat();
    @Override
    protected void attachBaseContext(Context newBase) {
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(newBase);
        String languageCode = prefs.getString("language", "en");
        super.attachBaseContext(updateResources(newBase, languageCode));
    }

    public Context updateResources(Context context, String languageCode) {
        Locale locale = new Locale(languageCode);
        Locale.setDefault(locale);

        Resources res = context.getResources();
        Configuration config = new Configuration(res.getConfiguration());
        config.setLocale(locale);
        LocaleList localeList = new LocaleList(locale);
        LocaleList.setDefault(localeList);
        config.setLocales(localeList);
        context = context.createConfigurationContext(config);
        return context;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.account);
        AppsManager.addActivity(this);

        user = GlobalData.getUser();

        user_info = findViewById(R.id.user_info);
        user_info.setOnClickListener(v -> {
            if (GlobalData.getUsername().equals("")){
                showRegistrationAlertDialog();
            }else {
                Intent intent = new Intent(Account.this, AccountInfo.class);
                startActivity(intent);
            }
        });

        updatePws = findViewById(R.id.updatePws);
        updatePws.setOnClickListener(v -> {
            if (GlobalData.getUsername().equals("")){
                showRegistrationAlertDialog();
            }else {
                Intent intent = new Intent(Account.this, AccountPws.class);
                startActivity(intent);
            }

        });

        clearAccount = findViewById(R.id.clearAccount);
        clearAccount.setOnClickListener(v -> {
            if (GlobalData.getUsername().equals("")){
                showRegistrationAlertDialog();
            }else {
                verification();
            }
        });

        login_out = findViewById(R.id.login_out);
        if (GlobalData.getUsername().equals("")){
            login_out.setText(R.string.account_tips);
        }
        login_out.setOnClickListener(v -> {
            GlobalData.reset();

            SharedPreferences preferences = getSharedPreferences("SignUp", Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = preferences.edit();
            editor.clear();
            editor.apply();


            Intent intent = new Intent(Account.this, Login.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
            startActivity(intent);
            finish();
        });
    }

    private void showRegistrationAlertDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(R.string.login_is_required)
                .setMessage(R.string.login_is_required_message)
                .setPositiveButton(R.string.login, (dialog, which) -> {
                    dialog.dismiss();
                    Intent intent = new Intent(this, Login.class);
                    startActivity(intent);
                    AppsManager.finishAll();
                }).setNegativeButton(R.string.cancel, (dialog, which) -> dialog.dismiss()).setCancelable(false)
                .show();
    }

    private void verification() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        View dialogView = LayoutInflater.from(this).inflate(R.layout.verification, null);
        EditText etVerification = dialogView.findViewById(R.id.et_verification);
        ProgressBar progressBar = dialogView.findViewById(R.id.progressBar);
        progressBar.setVisibility(View.INVISIBLE);

        builder.setView(dialogView);
        builder.setTitle(R.string.cancel_account);
        builder.setMessage(R.string.cancel_account_message);
        builder.setPositiveButton(R.string.confirm, null);
        builder.setNegativeButton(R.string.cancel, null);
        builder.setCancelable(false);

        AlertDialog dialog = builder.create();
        dialog.setOnShowListener(dlg -> {
            Button positiveButton = dialog.getButton(AlertDialog.BUTTON_POSITIVE);
            positiveButton.setOnClickListener(view -> {
                String verification = etVerification.getText().toString().trim();

                if ("yes".equals(verification.toLowerCase(Locale.ROOT))) {

                    progressBar.setVisibility(View.VISIBLE);

                    UserWithChat userWithChat = new UserWithChat();
                    userWithChat.setObjectId(user.getObjectId());
                    userWithChat.delete(new UpdateListener() {
                        @Override
                        public void done(BmobException e) {
                            if (e != null){
                                Log.e("e7",e.toString());
                            }
                        }
                    });

                    BmobBatch batch = new BmobBatch();
                    BmobQuery<ChatHistory> chatHistoryBmobQuery = new BmobQuery<>();
                    List<BmobObject> objects = new ArrayList<>();
                    chatHistoryBmobQuery.doSQLQuery("select * from ChatHistory where userId = '"+user.getObjectId()+"'", new SQLQueryListener<ChatHistory>() {
                        @Override
                        public void done(BmobQueryResult<ChatHistory> bmobQueryResult, BmobException e) {
                            if (e==null){
                                List<ChatHistory> results = bmobQueryResult.getResults();
                                for (ChatHistory result : results) {
                                    Log.e("ChatHistory", result.getObjectId());
                                    objects.add(result);
                                }
                            }
                            batch.deleteBatch(objects).doBatch(new QueryListListener<BatchResult>() {
                                @Override
                                public void done(List<BatchResult> list, BmobException e) {
                                    if (e != null){
                                        Log.e("batch",e.toString());
                                    }
                                }
                            });
                        }
                    });
                    BmobBatch batch2 = new BmobBatch();
                    BmobQuery<UserQuery> userQueryBmobQuery = new BmobQuery<>();
                    List<BmobObject> categoriesDelete2 = new ArrayList<>();
                    userQueryBmobQuery.doSQLQuery("select * from UserQuery where userId = '" + user.getObjectId() + "'", new SQLQueryListener<UserQuery>() {
                        @Override
                        public void done(BmobQueryResult<UserQuery> bmobQueryResult, BmobException e) {
                            if (e==null){
                                List<UserQuery> results = bmobQueryResult.getResults();
                                for (UserQuery result : results) {
                                    Log.e("UserQuery", result.getObjectId());
                                    categoriesDelete2.add(result);
                                }
                            }
                            batch2.deleteBatch(categoriesDelete2).doBatch(new QueryListListener<BatchResult>() {
                                @Override
                                public void done(List<BatchResult> list, BmobException e) {
                                    if (e==null){
                                        new Handler(Looper.getMainLooper()).postDelayed(() -> {
                                            progressBar.setVisibility(View.GONE);
                                            dialog.dismiss();
                                            if (currentToast != null) {
                                                currentToast.cancel();
                                            }
                                            currentToast = Toast.makeText(Account.this, R.string.cancel_account_tips, Toast.LENGTH_SHORT);
                                            currentToast.show();
                                            Intent intent = new Intent(Account.this, Login.class);
                                            startActivity(intent);
                                            AppsManager.finishAll();
                                        }, 2000);
                                    }else {
                                        Log.e("batch2",e.toString());
                                        currentToast = Toast.makeText(Account.this, R.string.cancel_account_tips2, Toast.LENGTH_SHORT);
                                    }
                                }
                            });
                        }
                    });
                } else {
                    if (currentToast!=null){
                        currentToast.cancel();
                    }
                    currentToast = Toast.makeText(this, R.string.cancel_account_tips3, Toast.LENGTH_SHORT);
                    currentToast.show();
                    etVerification.setError("'"+R.string.cancel_account_tips3+"'");
                    etVerification.setText("");
                }
            });

            Button negativeButton = dialog.getButton(AlertDialog.BUTTON_NEGATIVE);
            negativeButton.setOnClickListener(view -> dialog.dismiss());
        });

        dialog.show();
    }
}
